package com.doudou.collection.security;

import com.doudou.collection.mapper.UserMapper;
import com.doudou.collection.pojo.vo.UserVO;
import com.doudou.collection.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName UserDetailsServiceImpl
 * @Description Security认证流程实现类
 * @Author blue sky
 * @Date 2023/6/1 23:35
 * @Version 1.0
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("启动Security认证流程");

        UserVO userVO;
        //判断传过来的username是用户名还是邮箱或者手机号
        if (!RegexUtils.isPhoneInvalid(username)) {
            //是否为手机号
            userVO = userMapper.queryByPhone(username);
        } else if (!RegexUtils.isEmailInvalid(username)) {
            //是否为邮箱
            userVO = userMapper.queryByEmail(username);
        } else {
            //走到这一步说明是用户名
            userVO = userMapper.queryByUsername(username);
        }

        if (userVO == null) {
            return null;
        }

        List<GrantedAuthority> list = AuthorityUtils.createAuthorityList("ADMIN");
        return new CustomUserDetails(userVO, list);
    }
}
